package com.ktwlsoft.archivemanage.domain.business.businessService.guiBusiness;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.NotifyMessageRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.GuidanceApplyRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.NotifyMessage;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.GuidanceApply;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 指导申请
 *
 * @author zhuhe on 2020/4/28 14:08
 * @version 1.0
 */
@Component
public class GuidanceApplyService {

    private final GuidanceApplyRepositoryService guidanceApplyRepositoryService;

    private final NotifyMessageRepositoryService notifyMessageRepositoryService;

    public GuidanceApplyService(GuidanceApplyRepositoryService guidanceApplyRepositoryService, NotifyMessageRepositoryService notifyMessageRepositoryService) {
        this.guidanceApplyRepositoryService = guidanceApplyRepositoryService;
        this.notifyMessageRepositoryService = notifyMessageRepositoryService;
    }

    /**
     * 指导申请列表 on 2020/4/28 14:45
     *
     * @param state             state
     * @param guidanceTimeStart guidanceTimeStart
     * @param guidanceTimeEnd   guidanceTimeEnd
     * @param keyWords          keyWords
     * @return Result<?>
     */
    public Result<?> findPage(int pn, int pageSize, Integer state, String guidanceTimeStart, String guidanceTimeEnd, String keyWords, String type) {
        if (guidanceTimeStart != null && !"".equals(guidanceTimeStart)) {
            guidanceTimeStart = DateUtils.dayMinTime(guidanceTimeStart);
        }
        if (guidanceTimeEnd != null && !"".equals(guidanceTimeEnd)) {
            guidanceTimeEnd = DateUtils.dayMaxTime(guidanceTimeEnd);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state", state);
        jsonObject.put("guidanceTimeStart", guidanceTimeStart != null?guidanceTimeStart:"");
        jsonObject.put("guidanceTimeEnd", guidanceTimeEnd != null?guidanceTimeEnd:"");
        jsonObject.put("keyWords", keyWords);
        jsonObject.put("type", type);
        if("userWeb".equals(type)){
            Account account = UserPrincipal.getCurrentUser();
            if(account == null){
                return Result.body(null,ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
            }
            jsonObject.put("loginId", account.getId());
        }
        PageInfo<JSONObject> pageInfo = guidanceApplyRepositoryService.applyFindPage(pn, pageSize, jsonObject);
        return Result.ok(pageInfo);
    }

    /**
     * 指导申请新增 on 2020/4/28 14:52
     *
     * @param apply apply
     * @return Result<?>
     */
    public Result<?> save(GuidanceApply apply) {
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            return Result.body(apply, ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        if (apply.getUnitId() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("立档单位id为空");
        }
        if (apply.getUnitName() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("立档单位名称为空");
        }
        if (apply.getPosition() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("位置为空");
        }
        if (apply.getApplicantName() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人为空");
        }
        if (apply.getApplicantId() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人id为空");
        }
        if (apply.getApplicantPhone() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人电话为空");
        }
        if (apply.getContent() == null || "".equals(apply.getContent())) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导内容为空");
        }
        if (apply.getGuidanceTimeStart() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导开始时间为空");
        }
        if (apply.getGuidanceTimeEnd() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导结束时间为空");
        }
        apply.setId(SnowFlake.getNextId());
        apply.setApplyNum(guidanceApplyRepositoryService.getApplyNum(account));
        apply.setApplicantTime(new Date());
        apply.setCreateName(account.getRealName());
        apply.setCreateId(account.getId());
        apply.setCreateTime(new Date());
        apply.setUpdateName(account.getRealName());
        apply.setUpdateId(account.getId());
        apply.setUpdateTime(new Date());
        apply.setState(1);
        try {
            guidanceApplyRepositoryService.insert(apply);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(apply.getId());
    }

    /**
     * 提交 on 2020/4/28 15:45
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> commit(Long id) {
        GuidanceApply apply = guidanceApplyRepositoryService.getById(id);
        if (apply == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        apply.setState(2);
        try {
            guidanceApplyRepositoryService.update(apply);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        Account account = UserPrincipal.getCurrentUser();
        notifyMessageRepositoryService.insertNotifyMessage(
                apply.getId(),
                NotifyMessage.RemindType.GUIDANCE_APPLY_COMMIT,
                String.format("【档案业务指导服务系统】指导申请已提交提醒(%s,申请指导时间:%s - %s)",
                        apply.getUnitName(),
                        DateUtils.dateToStr(apply.getGuidanceTimeStart(),"yyyy-MM-dd"),
                        DateUtils.dateToStr(apply.getGuidanceTimeEnd(),"yyyy-MM-dd")),
                NotifyMessage.BelongBusiness.GUIDANCE_APPLY,
                apply.getApplicantName(),
                apply.getApplicantId(),
                account != null?account.getRealName():"",
                account != null?account.getId():0L,
                0
        );
        return Result.ok(id);
    }

    /**
     * 指导申请更新 on 2020/4/28 15:49
     *
     * @param apply apply
     * @return Result<?>
     */
    public Result<?> update(GuidanceApply apply) {
        Account account = UserPrincipal.getCurrentUser();
        if (account == null) {
            return Result.body(apply, ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        if (apply.getUnitId() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("立档单位id为空");
        }
        if (apply.getUnitName() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("立档单位名称为空");
        }
        if (apply.getPosition() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("位置为空");
        }
        if (apply.getApplicantName() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人为空");
        }
        if (apply.getApplicantId() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人id为空");
        }
        if (apply.getApplicantPhone() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("申请人电话为空");
        }
        if (apply.getContent() == null || "".equals(apply.getContent())) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导内容为空");
        }
        if (apply.getGuidanceTimeStart() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导开始时间为空");
        }
        if (apply.getGuidanceTimeEnd() == null) {
            return Result.body(apply.getUnitId(), ResultType.CHECK_ERROR).withMessage("期望指导结束时间为空");
        }
        apply.setUpdateName(account.getRealName());
        apply.setUpdateId(account.getId());
        apply.setUpdateTime(new Date());
        try {
            guidanceApplyRepositoryService.update(apply);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(apply.getId());
    }

    /**
     * 详情 on 2020/4/28 15:52
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> details(Long id) {
        GuidanceApply apply = guidanceApplyRepositoryService.getById(id);
        if (apply == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        return Result.ok(apply);
    }

    /**
     * 删除 on 2020/4/28 15:56
     *
     * @param id id
     * @return Result<?>
     */
    public Result<?> delete(Long id) {
        GuidanceApply apply = guidanceApplyRepositoryService.getById(id);
        if (apply == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        try {
            guidanceApplyRepositoryService.deleteById(apply.getId());
        } catch (Exception e) {
            e.printStackTrace();
            Result.body(id, ResultType.BUSINESS_SUCCESS).withMessage("操作过程中出现错误");
        }
        return Result.ok(id);
    }

    /**
     * 验证 on 2020/4/28 16:19
     *
     * @param id           id
     * @param remark       remark
     * @param verification verification
     * @return Result<?>
     */
    public Result<?> verification(Long id, String remark, Boolean verification) {
        GuidanceApply apply = guidanceApplyRepositoryService.getById(id);
        if (apply == null) {
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        apply.setRemark(remark);
        if (verification) {
            apply.setState(4);
        } else {
            apply.setState(3);
        }
        try {
            guidanceApplyRepositoryService.update(apply);
        } catch (Exception e) {
            e.printStackTrace();
            Result.body(id, ResultType.BUSINESS_SUCCESS).withMessage("操作过程中出现错误");
        }
        saveLog(OperationLog.OperationType.VERIFY, apply.getUnitName() + "指导申请" + "("+ apply.getApplyNum() +")" + (verification?"验证通过":"验证不通过"));
        return Result.ok(id);
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description   描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description) {
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "指导申请",
                OperationLog.BusinessType.BUSINESS
        ));
    }
}